#-*-coding=utf-8--*--
'''
Created on 2014年2月26日
Updated multi-vendor function by yuchunhua-2013-03-04

@author: 陈勇兵
'''
from django.http import HttpResponse,HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson 
from django.views.decorators.csrf import csrf_exempt
import re,os,sys

import datetime
from django.utils import simplejson
import commands
import pxssh  
from ap_encode_decode import *
#remoteHost = '10.4.11.239'

sys.path.append(os.path.join(current_dir,'../'))
from base.PyMySQL import ConnectMySQL

from base.localConfig import baseLocalConfig
from localConfig import myLocalConfig
import sys,datetime
rawdb_host = baseLocalConfig.mysqlConfig['rawdb']['host']
#rawdb_host='172.20.1.38'
rawdb_user = baseLocalConfig.mysqlConfig['rawdb']['user']
rawdb_passwd = baseLocalConfig.mysqlConfig['rawdb']['passwd']
rawdb_db = baseLocalConfig.mysqlConfig['rawdb']['db']

myRawdb = ConnectMySQL(rawdb_host,rawdb_user,rawdb_passwd,rawdb_db)









class rawdataClass():
    def __init__(self):
        self.datas = {}
        self.roledatas = {}
        self.WitheList = ['222.92.13.226','218.2.133.213']
    @csrf_exempt
    def getMsgFromRawdata(self,request,top=100,device=''):
        
        
        #print request

        if request.GET.has_key('ap'):
            device = request.GET['ap']
        elif request.POST.has_key('ap'):
            device = request.POST['ap']
        else:
            device = None
        if device==None:
            return HttpResponse('ap错误,请联系芝麻.')
        remote_addr = request.META['REMOTE_ADDR']
        
#         if remote_addr not in self.WitheList and not request.user.is_authenticated():
#             try:
#                 device = ap_decode(device)
#             except:
#                 return HttpResponse('ap错误,请联系芝麻.')
            #return HttpResponse('请使用地址/msg/?ap=***')
#         try:
#             device = ap_decode(device)
#         except:
#             return HttpResponse('ap错误,请联系芝麻.')
#         try:
#             mac = request.GET['mac']
#         except:
#             mac = request.POST['mac']

        if request.GET.has_key('mac'):
            mac = request.GET['mac']
        elif request.POST.has_key('mac'):
            mac = request.POST['mac']
        else:
            mac = None
        
        day = datetime.date.today().strftime('%Y-%m-%d')
        #print "day:",day
        #day = '2014-12-07'

        xfile = myLocalConfig.kafkaConfig['rawdata']['raw_file']
        cmd = 'grep %s %s '%(device,xfile)
        if mac!=None:
            mac = mac.lower()
            mac = re.sub('[^a-z0-9]','',mac)
            if len(mac)==12:
                mac = '%s:%s:%s:%s:%s:%s'%(mac[:2],mac[2:4],mac[4:6],mac[6:8],mac[8:10],mac[10:12])
            else:
                mac=None
        if mac!=None:
            cmd = cmd + ' | grep "%s"'%mac
        cmd = cmd +'| tail -n 2000'
        
        print cmd
        output = os.popen(cmd).read()

        datas = []
        areoScoutReg = "([\d]{4}-.*?) AreaScoutServerHandler [\d]+ WARN : sent msg\[([a-zA-Z0-9]+),01,([^,]+),\[([^,]+)\],([^\n]+)"
        nettyReg = "execute: ([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)\.(-[\d]+)\."
        rawdataReg = '\.([^\.]+)\.([^\.]+)\.([^\.]+)\.(-[\d]+)\.([^\n]+)'
        #for rtime , device,stime,mac,rssi in re.findall("",output):
        #2014-12-17.048d38586478.a8:57:4e:a7:8b:dc.23:59:58.-86.2014-12-18 00:00:00
        #for rtime,device,mac,stime,rssi in re.findall(nettyReg,output):
        for device,mac,stime,rssi,rtime in re.findall(rawdataReg,output):
            #print rtime
            datas.append('[ap mac] %s    [scan time] %s    [scan mac] %s    [rssi] %s'%( device,stime,mac,rssi))
        
        if not self.datas.has_key(device):
            self.datas[device]=[]
        ndatas = list(set(datas) - set(self.datas[device]))
        #ndatas = datas
        ndatas.reverse()
        
        
        #print 'data:',self.datas[device]
        if request.method=='GET':
            #return HttpResponse('<br/>'.join(msgs))
            return render_to_response(u'zmShowRawdata/rawdata_realtime.html',{},context_instance=RequestContext(request))
        else:
            if len(ndatas)!=0:
                self.datas[device] = datas
            print 'data length:',len(ndatas)
            #return HttpResponse('请使用地址/msg/?ap=***')
            return HttpResponse(simplejson.dumps({'datas':ndatas}))
 
 
 
    @csrf_exempt
    def getMsgFromRoledata(self,request,top=100,device=''):
        
        
        #print request

        if request.GET.has_key('group'):
            group = request.GET['group']
        elif request.POST.has_key('group'):
            group = request.POST['group']
        else:
            group = None
         

        
            
        if  group == None:
            return HttpResponse('group错误,请联系芝麻.')
        remote_addr = request.META['REMOTE_ADDR']
        


        if request.GET.has_key('mac'):
            mac = request.GET['mac']
        elif request.POST.has_key('mac'):
            mac = request.POST['mac']
        else:
            mac = None
        
        day = datetime.date.today().strftime('%Y-%m-%d')
        #print "day:",day
        #day = '2014-12-07'

        xfile = myLocalConfig.kafkaConfig['roledata']['raw_file']
        cmd = 'grep "group=%s," %s | tail -n 20'%(group,xfile)
        if mac!=None:
            mac = mac.lower()
            mac = re.sub('[^a-z0-9]','',mac)
            if len(mac)==12:
                mac = '%s:%s:%s:%s:%s:%s'%(mac[:2],mac[2:4],mac[4:6],mac[6:8],mac[8:10],mac[10:12])
            else:
                mac=None
        if mac!=None:
            cmd = cmd + ' | grep "%s"'%mac
        output = os.popen(cmd).read()

        datas = []

        for line in output.split('\n'):
            datas.append(line)
        
        if not self.roledatas.has_key(group):
            self.roledatas[group]=[]
        ndatas = list(set(datas) - set(self.roledatas[group]))
        #ndatas = datas
        ndatas.reverse()
        
        
        #print 'data:',self.datas[device]
        if request.method=='GET':
            #return HttpResponse('<br/>'.join(msgs))
            return render_to_response(u'zmShowRawdata/rawdata_realtime.html',{},context_instance=RequestContext(request))
        else:
            if len(ndatas)!=0:
                self.roledatas[device] = datas
            print 'data length:',len(ndatas)
            #return HttpResponse('请使用地址/msg/?ap=***')
            return HttpResponse(simplejson.dumps({'datas':ndatas}))
        
        
    @csrf_exempt
    def selectHistoryRaw(self,tab='device_coll_count',devices=[],startTime=None,endTime=None):
        if devices==[]:
            pass
        if startTime == None:
            startTime = (datetime.date.today() - datetime.timedelta(3)).strftime('%Y-%m-%d')
        if endTime == None:
            endTime = (datetime.date.today() - datetime.timedelta(1)).strftime('%Y-%m-%d')
        
        if devices==[]:
            sql = 'select device,day,count from %s where day >= "%s"'%(tab,startTime)
        elif len(devices)==1:
            sql = 'select device,day,count from %s where device="%s"  and day >= "%s"'%(tab,devices[0],startTime)
        else:
            sql = 'select device,day,count from %s where device in (%s)  and day >= "%s"'%(tab,'"'+'","'.join(devices)+'"',startTime)
        #print sql
        rets = myRawdb.SelectAll(sql)
        retDatas = {}
        if rets==[] or rets==None:
            pass
        else:
        
            for device,day,times in rets:
                day = day.strftime('%Y-%m-%d')
                times = int(times)
                if device not in retDatas.keys():
                    
                    retDatas[device] ={}
                if day not in retDatas[device].keys():
                    #retDatas[device] = {}
                    retDatas[device][day] = times
        datas = []
        mtime = (datetime.date.today() - datetime.timedelta(2)).strftime('%Y-%m-%d')
        days = [endTime,mtime,startTime]
        print retDatas
        if devices==[]:
            devices = retDatas.keys()
        for dev in devices:
            if dev not in retDatas.keys():
                datas.append([dev,None,None,None])
                continue
            data = [dev]
            for day in days:
                if day not in retDatas[dev].keys():
                    data.append(None)
                else:
                    data.append(retDatas[dev][day])
                print dev,day,data
                    
            datas.append(data)
            #print dev , data
        return datas
    @csrf_exempt
    def showHistoryRaw(self,request):
        if request.method=='GET':
            
            return render_to_response(u'zmShowRawdata/rawdata_history.html',{},context_instance=RequestContext(request))
        
        try:
            devicesStr = request.POST['devices']
            
            devices = []
            for devStr in devicesStr.split('\n'):
                device = re.sub('[^a-z0-9]','',devStr.lower())
                print 'device:%s'%device
                if len(device)!=12:continue
                devices.append(device)
        except:
            devicesStr = None
            devices = []
        
        datas = self.selectHistoryRaw(devices= devices)
        
        return render_to_response(u'zmShowRawdata/rawdata_history.html',{'datas':datas,'devices':devicesStr},context_instance=RequestContext(request))
        return HttpResponse(simplejson.dumps({'datas':datas,'devices':devicesStr}))
myRawdataClass = rawdataClass()






if __name__ == '__main__':
    pass
